package com.xfz.service;
import com.xfz.Mapper.UserMapper;
import com.xfz.User.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.UUID;
import com.xfz.User.User;
import org.springframework.util.DigestUtils;

//注册为注解
@Component
public class UserService {


    //    自动注入
    @Autowired
    UserMapper userMapper;

    public User register(User user) {
        User oldUser = userMapper.getUserByAccount(user.getAccount());
        if (oldUser != null) {
            return null;
        } else {
            // 同名账号不存在，才注册用户
            // 注册用户之前，使用MD5加密密码
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            if (userMapper.saveUser(user)>0) {
                // 注册成功，返回用户信息
                return user;
            } else {
                return null;
            }
        }
    }

    public User login(User user) {
        User loginUser = userMapper.getUserByAccount(user.getAccount());
        String userPwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (loginUser != null && loginUser.getPassword().equals(userPwd)) {
            String token = UUID.randomUUID().toString();
            loginUser.setToken(token);
            userMapper.tokenAdd(token, loginUser.getId());
            return loginUser;


        } else {
            return null;
        }

    }

    public User getUserByToken(String token) {
        return userMapper.getUserByToken(token);
    }


    public  boolean updatepass(User user){
        User loginUser = userMapper.getUserByAccount(user.getAccount());
        if(user.getAccount().equals(loginUser.getAccount())){
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            userMapper.updatePwd(user.getPassword(),user.getAccount());
            return true;
        }else {
            return  false;
        }

    }


    public List<User> userNames() {
        return userMapper.userName();
    }
//
//    public boolean del(Integer id){
//       Integer  del= userMapper.deluser(id);
//       if(del>0){
//          return true;
//       }else {
//           return false;
//       }
//    }


    }







